import { createRouter, createWebHashHistory, RouterView } from 'vue-router'
import store from '@/store'
import { h } from 'vue'
const routes = [{
  // 一级路由
  path: '/',
  name: 'Layout',
  component: () => import('@/views/Layout.vue'),
  children: [{
    // 首页路由,二级路由
    path: '/',
    name: 'Home',
    component: () => import('@/views/home')

  },{
    path: '/category/:id',
    component: () => import('@/views/category')
  },{
    path: '/category/sub/:id',
    component: () => import('@/views/category/sub.vue')
  }, {
    path: '/product/:id',
    component: () => import('@/views/goods')

  }, {path: '/member',
  component: () => import('@/views/member/Layout.vue'),
  children: [{
    path: '/member',
    component: () => import('@/views/member/home/index.vue')
  },{
    path: '/member/order',
    // // vue3.0 需要有嵌套关系才能模糊匹配   
    component: {render:() => h(<RouterView/>)},
    children: [
      {path: '', component: () => import('@/views/member/order/index.vue')},
      {path: ':id', component: () => import('@/views/member/order/detail.vue')}
    ]


  }]}]
}, {
  path: '/login',
  name: 'Login',
  component: () => import('@/views/login/index.vue')
}, {
  path: '/login/callback', 
  component: () => import('@/views/login/callback.vue')
}, {
  path: '/cart',
  component: () => import('@/views/cart/index.vue')
}, {
  path: '/member/checkout',
  component: () => import('@/views/member/pay/checkOut.vue')
},{
  path: '/member/pay',
  component: () => import('@/views/member/pay/index.vue')
},{
  path: '/pay/callback', component: () => import('@/views/member/pay/result.vue')
}]
const router = createRouter({
  history: createWebHashHistory(),
  routes,
  // 切换路由，回到顶部
  scrollBehavior () {
      return {left: 0, top: 0 }
  }
})

//前置导航守卫
router.beforeEach((to, from , next) => {
   // 用户信息
   const { token } = store.state.user.profile
   if (to.path.startsWith('/member') && !token) {
    next({ path: '/login', query: { redirectUrl: to.fullPath } })
  }
  next()
})





export default router
